#ifndef _METAARGS_HELPER__
#define _METAARGS_HELPER__

#include <metalang99.h>
#include <metalang99/bool.h>
#include <metalang99/gen.h>
#include <metalang99/ident.h>
#include <metalang99/lang.h>
#include <metalang99/list.h>
#include <metalang99/util.h>

#include "metaargs.h"
#include "version.h"

#if !ML99_VERSION_COMPATIBLE(1, 13, 3)
#	error metalang99 >= 1.13.3 required
#endif

#ifndef METAARGS_HELPER_EXIT_FAILURE
#	define METAARGS_HELPER_EXIT_FAILURE (!0)
#endif
extern const char *__progname; /* NOLINT(bugprone-reserved-identifier) */

#define METAARGS_HELP_OPTION_DECL    ma_long(ma_l_none(ma_l_id(help)))
#define METAARGS_VERSION_OPTION_DECL ma_long(ma_l_none(ma_l_id(version)))

/* clang-format off */
#define METAARGS_END_DECL                                                       \
	METAARGS_HELP_OPTION_DECL, METAARGS_VERSION_OPTION_DECL
/* clang-format on */

#define EXPAND_PROGNAME(N) /* note: N must be in 1-9 range */                 \
	ML99_LIST_EVAL_COMMA_SEP(ML99_listTail(                               \
	    ML99_list(ML99_times(ML99_if(ML99_isDigit(v(N)), v(N), v(1)),     \
				 v(, __progname)))))

#define usage(S)                                                              \
	printf(usage_str, EXPAND_PROGNAME(NFORMAT));                          \
	putchar('\n');                                                        \
	return (S)

#define METAARGS_HELP_VERSION(config)                                         \
	if ((config).error) { usage(METAARGS_HELPER_EXIT_FAILURE); }          \
	if ((config).arg_help.is_set) { usage(0); }                           \
	if ((config).arg_version.is_set) {                                    \
		print_version();                                              \
		return 0;                                                     \
	}                                                                     \
	ML99_TRAILING_SEMICOLON()

#define METAARGS_PARSE(prog, cfg, argc, argv) \
	ArgsConfig_##prog cfg = parse_args_##prog(argc, argv); \
	METAARGS_HELP_VERSION(cfg)

#endif /* _METAARGS_HELPER__ */
